package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品 {}", dishDTO);

        dishService.saveWithFlaover(dishDTO);

        //清除缓存数据
        Long categoryId = dishDTO.getCategoryId();
        String pattern = "dash_" + categoryId;
        cleanCache(pattern);

        return Result.success();
    }

    /**
     * 分页查询
     */

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询 {}", dishPageQueryDTO);

        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);

        return Result.success(pageResult);
    }

    /**
     * 批量删除
     * dish?ids=47,48,46 传递参数
     * List<Long> ids 接收参数
     * 必须要添加@RequestParam 参数才可以映射上
     */

    @DeleteMapping
    @ApiOperation("批量删除")
    public Result delete(@RequestParam List<Long> ids){
        log.info("批量删除 {}", ids);

        dishService.delete(ids);

        //清空缓存数据
        cleanCache("dash_*");

        return Result.success();
    }

    /**
     * 根据id查询菜品和口味数据
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("根据id查询菜品和口味数据 {}", id);

        return Result.success(dishService.getByIdWithFlavor(id));
    }

    /**
     * 更新菜品和口味的数据
     */
    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("更新菜品和口味的数据 {}", dishDTO);

        dishService.update(dishDTO);

        //清空缓存数据
        cleanCache("dash_*");

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId){
        List<DishVO> list = dishService.list(categoryId);
        return Result.success(list);
    }

    /**
     * 根据表达式查早所有复合要求的key然后把他们都删除掉
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
